import os
from django.http import FileResponse
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_protect
from django.conf import settings
from django.middleware.csrf import get_token
from django.contrib.auth.hashers import make_password, check_password
from django.utils import timezone
from django.core.paginator import Paginator
from .models import User, Checkin, Transaction, Product
from .serializer import UserSerializer, CheckinSerializer, TransactionSerializer, ProductSerializer
from .tool import getRequestUser, getProductAppearance


@api_view(['GET'])
def get_csrf_token(request):
    """获取CSRF令牌"""
    token = get_token(request)
    return Response({'csrfToken': token})


@api_view(['GET'])
@csrf_protect
def check_session(request):
    """检查用户是否登录"""
    user_id = request.session.get('user_id')
    if user_id:
        return Response({'isLoggedIn': True})
    else:
        return Response({'isLoggedIn': False})
    
    
@api_view(['POST'])
@csrf_protect
def check_in(request):
    """用户登记"""
    username = request.data.get('username')
    password = request.data.get('password')

    if len(username) > 8:
        return Response({'message': '昵称过长'})

    if len(password) < 8:
        return Response({'message': '密码过短'})

    user, created = User.objects.get_or_create(
        username=username,
        defaults={'password': make_password(password)}  # 这里默认进行加密
    )   # 获取用户, 没有就创建
    

    if created:     # 没有, 创建好了
        request.session['user_id'] = user.id
        request.session.cycle_key()
        return Response({'message': '注册成功'})
    elif check_password(password, user.password):
        request.session['user_id'] = user.id
        request.session.cycle_key()
        return Response({'message': '登录成功'})
    else:
        return Response({'message': '密码错误'})


@api_view(['GET'])
@csrf_protect
def get_user(request):
    """获取用户信息"""
    # 获取 user_id
    user_id = request.session['user_id']
    if user_id:     # 若存在user_id
        try:
            user = User.objects.get(id=user_id)     # 获取该用户
        except User.DoesNotExist:   # 不存在该用户
            return Response({'message': 'not_exist'})
        
        serializer = UserSerializer(user)   # 获取序列化器
        return Response({'message': 'success', 'user_data': serializer.data})
    else:
        return Response({'message': 'no_user_id'})
    

@api_view(['GET'])
@csrf_protect
def get_check_data(request):
    """获取签到的天数"""
    # 获取用户
    user = getRequestUser(request)
    check_in = Checkin.objects.get_or_create(user=user)[0]

    serializer = CheckinSerializer(check_in)    # 获取序列化器
    getProductAppearance()
    return Response({'check_data': serializer.data})


@api_view(['GET'])
@csrf_protect
def check_one_day(request):
    """签到一天"""
    # 获取用户
    user = getRequestUser(request)

    # 获取今天的日期
    today = timezone.localdate()
    # yesterday = today - timedelta(days=1)

    # 获取到Chekin对象
    check_in = Checkin.objects.get(user=user)
    
    checkin_date = check_in.checkin_date
    day = check_in.day

    # 今天以及签到以及不是刚注册的用户
    if today == checkin_date and day != 0:
        return Response({'check_data': 'error'})
    
    # 对象更新数据
    if day % 7 == 0 and day != 0: 
        check_in.reward = 777
        user.gold += 777
    else:
        check_in.reward = 300
        user.gold += 300

    check_in.checkin_date = today
    check_in.day += 1

    # 保存对象
    user.save()
    check_in.save()

    # 返回序列化器
    serializer = CheckinSerializer(check_in)
    return Response({'check_data': serializer.data, 'gold': user.gold})


@api_view(['GET'])
@csrf_protect
def get_orders(request):
    """获取用户的所有已购商品"""
    # 获取用户
    user = getRequestUser(request)
    
    # 获取用户购买的所有订单

    response_data_list = []  # Response返回的数据
    

    # 过滤出有关用户的订单
    transaction_fileter_list = Transaction.objects.filter(buyer=user).distinct()

    # 整合序列化信息
    for i in transaction_fileter_list:
        order = TransactionSerializer(i).data
        product = ProductSerializer(i.product).data

        # 自定
        order['seller'] = User.objects.get(id=order['seller']).username

        response_data_list.append({
            'order': order,
            'product': product
        })

    return Response(response_data_list)

@api_view(['GET'])
@csrf_protect
def get_random_appearance(request):
    """获取随机商品外观"""
    return Response(getProductAppearance())


@api_view(['POST'])
@csrf_protect
def add_product(request):
    """制造一个商品"""
    # 获取用户
    user = getRequestUser(request)
    # 发送过来的数据
    data = request.data
    
    # 判断商品名是否重复
    is_repeat = Product.objects.filter(name=data['name']).exists()

    if data['price'] == 0:
        return Response({'message': 'zero'})
    
    # 如果商品名重复
    if is_repeat:
        return Response({'message': 'repeat'})

    if data['description'] == "":
        return Response({'message': 'description_none'})
    
    # 添加商品
    Product.objects.create(
        name=data['name'],
        price=data['price'],
        description=data['description'],
        expires_at=timezone.now() + timezone.timedelta(days=7), 
        owner=user,
        appearance={
            'colors': data['colors']
        }
    )

    return Response({'message': 'success'})


@api_view(['GET'])
@csrf_protect
def get_product(request):
    """获取用户制造的商品"""
    # 获取用户  
    user = getRequestUser(request)
    # 获取所有商品
    products = Product.objects.filter(owner=user)
    response_data_list = []

    for i in products:
        response_data_list.append(ProductSerializer(i).data)
    
    return Response({'data': response_data_list})


@api_view(['GET'])
@csrf_protect
def get_market_data(request):
    """获取集市东西"""
    # 获取用户
    user = getRequestUser(request)

    products = Product.objects.filter(sold=False).order_by('?')[:10]     # 获取随机数据
    # 创建分页的对象
    paginator = Paginator(products, 10)
    # 获取URL参数page
    page_number = request.GET.get('page')
    # 获取这一页的数据
    page_list = paginator.get_page(page_number).object_list
    # 增加作者
    serializers_list = []
    for i in page_list:
        serializer = ProductSerializer(i).data
        serializer['owner'] = User.objects.get(id=serializer['owner']).username

        if user.username == serializer['owner']:
            continue

        serializers_list.append(serializer)

    return Response({'data': serializers_list})

@api_view(['POST'])
@csrf_protect
def buy(request):
    """购买商品"""
    # 获取用户对象
    user = getRequestUser(request)
    # 获取要购买的物品对象
    product_id = request.data.get('product_id')
    product = Product.objects.get(id=product_id)

    if user.gold < product.price:
        return Response({'message': 'error'})

    # 创建订单对象
    Transaction.objects.create(
        product=product,
        buyer=user,
        seller=product.owner,
        price=product.price,
    )

    # 更新相关参数

    seller = User.objects.get(id=product.owner.id)
    product.sold = True
    seller.gold += product.price
    user.gold -= product.price

    product.save()
    user.save()
    seller.save()

    return Response({"message": f"商品: {product.name} 购买成功!"})

@api_view(['POST'])
@csrf_protect
def delete_product(request):
    # 获取要删除的物品对象
    product_id = request.data.get('product_id')
    product = Product.objects.get(id=product_id)

    product.delete()

    return Response({'message': '商品删除成功!'})


api_view(['GET'])
@csrf_protect
def heart(request):
    image_path = os.path.join(settings.BASE_DIR, 'public', '赞赏码.png')

    return FileResponse(open(image_path, 'rb'), content_type='image/png')
